package com.zhiche.lisa.integration.controller;

import com.lisa.json.JSONUtil;
import com.lisa.syslog.SysLogUtil;
import com.lisa.syslog.model.SysLogDataPo;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.enums.InterfaceEventEnum;
import com.zhiche.lisa.core.enums.RedisLogTypeEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.integration.dao.model.ProcessCallBack;
import com.zhiche.lisa.integration.dto.order.OTMEvent;
import com.zhiche.lisa.integration.dto.redisLog.LogExportPo;
import com.zhiche.lisa.integration.inteface.otm.OtmEventService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * Created by zhaoguixin on 2018/7/22.
 */
@RestController
@RequestMapping(value = "/event")
@Api(value = "/event", description = "事件处理", tags = {"事件处理"})
public class EventController {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OtmEventService otmEventService;
    @Value("${logRedis.isTest}")
    private boolean isTest;

    @PostMapping(value = "/export")
    @ApiOperation(value = "OTM事件导出", notes = "OTM事件导出",
            produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<String> eventExport(@RequestBody OTMEvent paramDTO) {
        RestfulResponse<String> result = new RestfulResponse<>(0, "成功", null);
        try {
            //记录事件导出已接收到日志系统
            addExportLogs(paramDTO, IntegrationURIEnum.EVENT_URI.getAddress(), 2, 1, "");

            String requestId = otmEventService.exportEvent(paramDTO);
            result.setData(requestId);

            //记录事件导出已接收到日志系统
            addExportLogs(paramDTO,IntegrationURIEnum.EVENT_URI.getAddress(), 3, 1, "");

            return result;
        } catch (Exception e) {
            addExportLogs(paramDTO,IntegrationURIEnum.EVENT_URI.getAddress(), 3, 0, e.getMessage());
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    /**
     * 添加日志记录到日志系统
     */
    public void addExportLogs(OTMEvent otmEvent, String uri, Integer dataStatus, Integer isSuc, String errCont) {
        try {
            if (Objects.nonNull(otmEvent)) {
                String tableIdx = RedisLogTypeEnum.EVENT_EXPORT.getCode();
                String sourceSystem = "";
                if (InterfaceEventEnum.BS_TRANS_ARRIVED.getCode().equals(otmEvent.getEventType())) {
                    sourceSystem = SystemEnum.OMS.getCode();
                } else {
                    sourceSystem = SystemEnum.WMS.getCode();
                }
                String targetSystem = SystemEnum.INTEGRATION.getCode();
                // 来源、目标系统表示
                // 目标API标示
                String key = sourceSystem + SystemEnum.UNDERLINE.getCode() + targetSystem;
                String fKey = uri + SystemEnum.UNDERLINE.getCode() + otmEvent.getExportKey() + SystemEnum.UNDERLINE.getCode() + otmEvent.getEventType() + SystemEnum.UNDERLINE.getCode() + dataStatus;
                String dtoJson = JSONUtil.toJsonStr(otmEvent);
                // 业务相关实体类
                LogExportPo logExportPo = new LogExportPo(sourceSystem, targetSystem, otmEvent.getEventType(), uri, otmEvent.getShipmentId(),
                        otmEvent.getOrderReleaseId(), otmEvent.getVin(), otmEvent.getOrderReleaseId(), otmEvent.getExportKey(), dtoJson, isSuc, errCont, 1, 0, dataStatus);
                SysLogDataPo sysLogDataPo = new SysLogDataPo(tableIdx, JSONUtil.toJsonStr(logExportPo));
                SysLogUtil.addSysLogs(key, fKey, sysLogDataPo, isTest);
            }
        } catch (Exception e) {
            logger.error("事件导出回传otm，添加日志异常" + e.getMessage());
        }
    }

    @PostMapping(value = "/callBack")
    @ApiOperation(value = "OTM回调接口", notes = "OTM回调接口", response = RestfulResponse.class)
    public RestfulResponse callBack(@RequestBody String callBackXml) {
        RestfulResponse<ProcessCallBack> result = new RestfulResponse<>(0, "成功", null);
        try {
            ProcessCallBack callBack = otmEventService.callBack(callBackXml);
            result.setData(callBack);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }

    }

    @PostMapping(value = "/getProcessResult")
    @ApiOperation(value = "获取事件处理结果", notes = "获取事件处理结果(OTM异步处理结果)",
            produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<ProcessCallBack> getProcessResult(@RequestParam("requestId") String requestId) {
        RestfulResponse<ProcessCallBack> result = new RestfulResponse<>(0, "成功", null);
        try {
            ProcessCallBack callBack = otmEventService.getProcessResult(requestId);
            result.setData(callBack);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
            return result;
        }
    }
}
